<script setup lang="ts">
import type { OptionItem } from '@/types/common';
import SelectorGroup from './selector-group.vue';
import { useAccCommon } from '../composables/use-acc-common';

interface IProps {
  filterShow: boolean;
  filterVal: any;
  tranposList: OptionItem[];
  logistList: OptionItem[];
  userList: OptionItem[];
  reasonList: OptionItem[];
  fetchLogistList: (tranposId: number) => Promise<void>;
  fetchUserList: (tranposId: number, logistCenterId: number) => Promise<void>;
}

const props = withDefaults(defineProps<IProps>(), {
  filterShow: false,
  filterVal: () => ({}),
  tranposList: () => [],
  logistList: () => [],
  userList: () => [],
  reasonList: () => [],
});

// 事件定义
const emit = defineEmits(['confirm', 'update:filterShow']);

// 内部状态
const localFilterVal = ref({ ...props.filterVal });

// 监听 props 变化，同步到内部状态
watch(
  () => props.filterVal,
  newVal => {
    localFilterVal.value = { ...newVal };
  }
);

const calendarRef = ref();

// 使用优化后的 useAccCommon
const { showStates, selectHandlers, closeHandlers } = useAccCommon({
  onSelect: async (type, item) => {
    // 根据类型设置对应的字段值
    if (type === 'address') {
      localFilterVal.value.tranposId = item.id;
      localFilterVal.value.tranposName = item.name;
      // 选择运输地址后，清空物流中心和直调人员
      localFilterVal.value.logistCenterId = '';
      localFilterVal.value.logistCenterName = '';
      localFilterVal.value.directrgMan = '';
      // 查询物流中心列表
      await props.fetchLogistList(item.id);
    } else if (type === 'logistics') {
      localFilterVal.value.logistCenterId = item.id;
      localFilterVal.value.logistCenterName = item.name;
      // 选择物流中心后，清空直调人员
      localFilterVal.value.directrgMan = '';
      // 查询直调人员列表
      if (localFilterVal.value.tranposId) {
        await props.fetchUserList(localFilterVal.value.tranposId, item.id);
      }
    } else if (type === 'user') {
      // user 类型只有 name，没有 id
      localFilterVal.value.directrgMan = item.name;
    } else if (type === 'reason') {
      localFilterVal.value.reasonId = item.id;
      localFilterVal.value.reasonName = item.name;
    }
  },
});

// 确认筛选
const handleFilterConfirm = () => {
  emit('update:filterShow', false);
  emit('confirm', localFilterVal.value);
};

// 重置筛选
const reset = () => {
  localFilterVal.value = {
    orderId: '',
    start: '',
    end: '',
    tranposId: '',
    tranposName: '',
    logistCenterId: '',
    logistCenterName: '',
    reasonId: '',
    reasonName: '',
    directrgMan: '',
  };
};

const handleDateConfirm = (value: any) => {
  localFilterVal.value.start = value.range.before;
  localFilterVal.value.end = value.range.after;
};

const handleClickLogist = () => {
  if (localFilterVal.value.tranposId) {
    showStates.logistics = true;
  } else {
    showToast('请先选择运输地址');
  }
};

const handleClickUser = () => {
  if (localFilterVal.value.logistCenterId) {
    showStates.user = true;
  } else {
    showToast('请先选择物流中心');
  }
};
</script>

<template>
  <up-popup
    :show="filterShow"
    :zIndex="997"
    mode="bottom"
    round="16"
    @close="emit('update:filterShow', false)"
  >
    <up-form borderBottom>
      <app-form-item label="总单ID">
        <up-input
          v-model="localFilterVal.orderId"
          clearable
          placeholder="点击输入总单ID"
          inputAlign="right"
          fontSize="28rpx"
          border="none"
        >
        </up-input>
      </app-form-item>
      <app-form-item label="时间范围">
        <view
          :class="`w-full text-right ${localFilterVal.start || localFilterVal.end ? '' : 'color-gray-6'}`"
          @click="calendarRef?.open()"
        >
          {{
            localFilterVal.start || localFilterVal.end
              ? `${localFilterVal.start} 至 ${localFilterVal.end}`
              : '点击选择时间范围'
          }}
        </view>
      </app-form-item>
      <app-form-item label="运输地点">
        <view
          :class="`w-full text-right ${localFilterVal.tranposId ? '' : 'color-gray-6'}`"
          @click="showStates.address = true"
        >
          {{ localFilterVal.tranposName || '点击选择运输地址' }}
        </view>
      </app-form-item>
      <app-form-item label="物流中心">
        <view
          :class="`w-full text-right ${localFilterVal.logistCenterId ? '' : 'color-gray-6'}`"
          @click="handleClickLogist"
        >
          {{ localFilterVal.logistCenterName || '点击选择物流中心' }}
        </view>
      </app-form-item>
      <app-form-item label="直调人员">
        <view
          :class="`w-full text-right ${localFilterVal.directrgMan ? '' : 'color-gray-6'}`"
          @click="handleClickUser"
        >
          {{ localFilterVal.directrgMan || '点击选择直调人员' }}
        </view>
      </app-form-item>
      <app-form-item label="直调原因" :borderBottom="false">
        <view
          :class="`w-full text-right ${localFilterVal.reasonId ? '' : 'color-gray-6'}`"
          @click="showStates.reason = true"
        >
          {{ localFilterVal.reasonName || '点击选择直调原因' }}
        </view>
      </app-form-item>
    </up-form>
    <view class="h-160 flex items-center justify-space-evenly px-4">
      <up-button shape="circle" @click="reset">重置</up-button>
      <up-button class="ml-4" shape="circle" type="primary" @click="handleFilterConfirm"
        >确认</up-button
      >
    </view>
  </up-popup>
  <app-calendar ref="calendarRef" mode="range" @confirm="handleDateConfirm" />
  <selector-group
    :tranposList="tranposList"
    :logistList="logistList"
    :userList="userList"
    :reasonList="reasonList"
    :showStates="showStates"
    :selectHandlers="selectHandlers"
    :closeHandlers="closeHandlers"
  />
</template>
